// const SMSClient = require('@alicloud/sms-sdk')
const accessKeyId = 'N311162_N4146445'
const secretAccessKey = 'zrgcWqty4l6e01'
var http = require('http')
var https = require('https')
var querystring = require("querystring")
var smsuri = "/msg/send/json"
var smshost = "smssh1.253.com"
module.exports = function(app) {
	return new Remote(app);
};

var Remote = function(app) {
	this.app = app;
	Remote.GameService = this.app.get("GameService")
	//验证码列表
	Remote.captchaList = {}
    Remote.dbService = this.app.get("dbService")
    if(Remote.dbService && Remote.dbService.db){
    	Remote.db = Remote.dbService.db
    }
};
var remote = Remote.prototype
var local = {}

//请求发送验证码
remote.sendCaptcha = function(phone,cb) {
	var tmpCode = Math.floor(Math.random() * 8999) + 1000
	var msg="【大自然】您的验证码是"+tmpCode+"。如非本人操作，请忽略。";
	var post_data = JSON.stringify({
		"account" : accessKeyId,
		"password" : secretAccessKey,
		"phone" : phone,
		"msg" : msg,
		"report" : "false"
	})
	post(smsuri,post_data,smshost,function(data) {
		data = JSON.parse(data[0])
		if(data.code == 0){
			Remote.captchaList[phone] = {"code" : tmpCode,"phone" : phone}
			cb(true,data)
		}else{
			cb(false,data)
		}
	})
}
//注册手机号
remote.register = function(phone,password,code,referrer,cb) {
	var self = this
	if(Remote.captchaList[phone] && Remote.captchaList[phone].code == code){
		delete Remote.captchaList[phone]
		Remote.dbService.db.hget("game:phoneAccount",phone,function(err,data) {
			if(data){
				console.log(err,data)
				cb(false,"账号已存在")
				return
			}
			Remote.dbService.db.hset("game:phoneAccount",phone,password)
			var result = {
				nickname : "unknown&%",
				phone : phone,
				referrer : referrer,
				headimgurl : 0,
				unionid : phone,
				openid : phone
			}
			self.app.rpc.db.remote.createAccount(null,result,function(flag) {
				cb(flag)
			})
		})
	}else{
		cb(false,"验证码错误")
	}
}

//重置密码
remote.changePassword = function(phone,password,code,cb) {
	if(Remote.captchaList[phone] && Remote.captchaList[phone].code == code){
		delete Remote.captchaList[phone]
		this.app.rpc.db.remote.changePassword(null,phone,password,function(flag,data) {
			cb(flag,data)
		})
	}else{
		cb(false,"验证码错误")
	}
}
var post = function(uri,content,host,cb){
	var options = {  
        hostname: host,
        port: 80,  
        path: uri,  
        method: 'POST',  
        headers: {  
            'Content-Type': 'application/json; charset=UTF-8', 
        }  
    };
    var req = http.request(options, function (res) {  
		var responseText=[];
		var size = 0;
        res.setEncoding('utf8');  
		res.on('data', function (data) {
		  responseText.push(data);
		  size+=data.length;
		});
		res.on('end', function () {
		  cb(responseText)
		});
    }); 
    req.write(content);
    req.end();   
}